package com.whvronk.server.handler;

import com.whvronk.server.operation.OperationResult;
import com.whvronk.server.operation.RequestMessage;
import com.whvronk.server.operation.ResponseMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.context.ApplicationContext;

/**
 * 主要是用于处理客户端发送到服务器的RequestMessage并且根据请求内容执行相应的业务逻辑
 * 最终将处理的结果作为响应消息返回给客户端
 * 这里是得到了一个ResponseMessage
 */
public class DataServerProcessHandler extends SimpleChannelInboundHandler<RequestMessage> {
    private final ApplicationContext applicationContext;

    public DataServerProcessHandler(ApplicationContext applicationContext) {
        super();
        this.applicationContext = applicationContext;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RequestMessage requestMessage) throws Exception {

        /*
            1.获取并执行RequestMessage的业务逻辑，返回OperationResult结果
            2.创建ResponseMessage对象，并设置与请求消息相同的消息头。
            3.将业务处理结果设置为ResponseMessage的消息体。
            4.通过 channelHandlerContext.writeAndFlush 方法将响应消息发送出去给客户端
         */
        OperationResult result = requestMessage.getMessageBody().execute(applicationContext);

        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setMessageHeader(requestMessage.getMessageHeader());
        responseMessage.setMessageBody(result);

        channelHandlerContext.writeAndFlush(responseMessage);
    }
}
